using System;
using System.Text;
using System.Web.UI.WebControls;
using HelpdeskServices.Properties;

public partial class Default : System.Web.UI.Page
    {
        private const int systemRowIdentifier = 5;
        protected void Page_Load(object sender, EventArgs e)
        {
            

            StringBuilder clientSideScript = new StringBuilder();
            clientSideScript.Append("<script language=JavaScript> ");
            clientSideScript.Append("function setLookup( FirstName, LastName, contactId)");
            clientSideScript.Append("{");
            clientSideScript.Append("var lookupData = new Array(); ");
            clientSideScript.Append("var lookupItem = new Object();  ");
            clientSideScript.Append("lookupItem.id = contactId ;  ");
            clientSideScript.Append("lookupItem.name= FirstName + ' ' + LastName ;");
            clientSideScript.Append("lookupItem.typename='contact';");
            clientSideScript.Append("lookupData[0] = lookupItem; ");
            clientSideScript.Append("parent.document.crmForm.customerid.DataValue = lookupData;");
            clientSideScript.Append("parent.document.crmForm.all.IFRAME_SearchFrame.parentElement.parentElement.parentElement.style.display = 'none';");
            clientSideScript.Append("}");
            clientSideScript.Append("</script>");


            if (!Page.ClientScript.IsClientScriptBlockRegistered(clientSideScript.ToString()))
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "script", clientSideScript.ToString());
            };
        }
        /// <summary>
        /// Scripts to attach to client side button click.
        /// </summary>
        /// <param name="row">The row.</param>
        /// <returns></returns>
        private static string scriptToAttachToClientSideButtonClick(GridViewRow row)
        {
            StringBuilder javascriptToAppend = new StringBuilder();
            javascriptToAppend.AppendFormat("javascript:setLookup('{0}','{1}','{2}');",
                row.Cells[1].Text,
                row.Cells[2].Text,
                row.Cells[4].Text);
            return javascriptToAppend.ToString();

        }
        /// <summary>
        /// Scripts to attach to client side button click, with the diffrince being the guid, in this case being wrapped with braces
        /// </summary>
        /// <param name="row">The row.</param>
        /// <param name="entityId">The entity id.</param>
        /// <returns></returns>
        private static string scriptToAttachToClientSideButtonClick(GridViewRow row, Guid entityId)
    {
            //ToTest: Check that entityid is correctly wrapped in braces
         StringBuilder javascriptToAppend = new StringBuilder();
            javascriptToAppend.AppendFormat("javascript:setLookup('{0}','{1}','{2}');"
                                            , row.Cells[1].Text
                                            , row.Cells[2].Text
                                            , string.Concat("{",entityId,"}"));
        return javascriptToAppend.ToString();
    }
        /// <summary>
        /// Handles the SelectedIndexChanged event of the SearchResultsGrid control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void SearchResultsGrid_SelectedIndexChanged(object sender, EventArgs e)
        {
            GridView localSearchResult = (GridView)sender;
            
            string systemIdentifier = localSearchResult.SelectedRow.Cells[systemRowIdentifier].Text;

            if (systemIdentifier.Length == 32)
            {
                Contact contact = new Contact();
                contact.ShopperId = systemIdentifier;
                contact.CreateInCrm();
                Guid contactImportedGuid = contact.ContactIdInCrm;
                LinkButton linkButton = (LinkButton)localSearchResult.SelectedRow.Cells[0].Controls[0];
                linkButton.OnClientClick = scriptToAttachToClientSideButtonClick(localSearchResult.SelectedRow, contactImportedGuid);
                //Hack: Client script could be registered more ellegant, but at this point it works, if nothing changes <see cref="System.Duh"/>
                Page.RegisterClientScriptBlock("", scriptToAttachToClientSideButtonClick(localSearchResult.SelectedRow, contactImportedGuid).Replace("javascript:", "<script language=JavaScript>")+"</script>");
                localSearchResult.DataBind();
            }

        }
        protected void SearchResultsGrid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string systemIdentifier = e.Row.Cells[systemRowIdentifier].Text;
                if (systemIdentifier.Length == 38)
                {
                    LinkButton SelectButton = (LinkButton)e.Row.Cells[0].Controls[0];
                    SelectButton.PostBackUrl = scriptToAttachToClientSideButtonClick(e.Row);
                    SelectButton.OnClientClick = scriptToAttachToClientSideButtonClick(e.Row);
                }
                else
                {
                    LinkButton SelectButton = (LinkButton)e.Row.Cells[0].Controls[0];
                    SelectButton.Text = "Import";
                }
            }
        }
}
